#include "chat.h"
#include "ui_chat.h"
#include "user.h"
#include "mainwindow.h"
//以下为三个功能函数的库
#include <QtMultimedia/QSound>
#include <QtGui/QPalette>
#include <QtGui/QColor>
#include <QtGui/QStandardItemModel>
#include <QtWidgets/QVBoxLayout>
#include <QtGui/QStandardItem>
#include <QtGui/QPixmap>
#include <QApplication>
#include <QKeySequence>

Chat::Chat(QTcpSocket* s,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Chat)
{
    QWidget *widget = new QWidget;
    // 创建数据模型
    QStandardItemModel *colorModel = new QStandardItemModel(widget);

    QColor pinkColor(246,190,200);
    QStandardItem *pinkItem = new QStandardItem("桃夭");
    pinkItem->setData(pinkColor, Qt::UserRole); // 存储颜色数据
    colorModel->appendRow(pinkItem);

    QColor blueColor(129,216,208);
    QStandardItem *blueItem = new QStandardItem("蒂凡尼蓝");
    blueItem->setData(blueColor, Qt::UserRole); // 存储颜色数据
    colorModel->appendRow(blueItem);

    QColor whiteColor(234,220,196);
    QStandardItem *whiteItem = new QStandardItem("伊莎贝拉色");
    whiteItem->setData(whiteColor, Qt::UserRole); // 存储颜色数据
    colorModel->appendRow(whiteItem);

    QColor purpleColor(204,164,227);
    QStandardItem *purpleItem = new QStandardItem("丁香色");
    purpleItem->setData(purpleColor, Qt::UserRole); // 存储颜色数据
    colorModel->appendRow(purpleItem);

    ui->setupUi(this);

    ui->colorListView->setModel(colorModel);
    ui->colorListView->hide();
    ui->closeButton->hide();
    ui->changeButton->hide();
    ui->sendButton->setShortcut(QKeySequence("Return"));//回车快捷键


    socket=s;
    //socket->abort();
    connect(socket,&QTcpSocket::readyRead,this,&Chat::dealClientRead);
    connect(ui->fileButton, &QPushButton::clicked, this, &Chat::selectFile);
    qDebug()<<m_filePath;

    QStringList headerLabels;
    headerLabels << "ID" << "Name" << "IP";
    ui->onlinetableWidget->setHorizontalHeaderLabels(headerLabels);

    QHeaderView *horizontalHeader = ui->onlinetableWidget->horizontalHeader(); // Set the width for specific header sections
    horizontalHeader->resizeSection(0, 60); // Set width of the first header section to 50 pixels
    horizontalHeader->resizeSection(1, 105); // Set width of the second header section to 150 pixels
    horizontalHeader->resizeSection(2, 100); // Set width of the third header section to 100 pixels

    QTableWidgetItem *item1 = new QTableWidgetItem("1");
    QTableWidgetItem *item2 = new QTableWidgetItem("John Doe");
    QTableWidgetItem *item3 = new QTableWidgetItem("192.168.1.1");
    ui->onlinetableWidget->setItem(0, 0, item1);
    ui->onlinetableWidget->setItem(0, 1, item2);
    ui->onlinetableWidget->setItem(0, 2, item3);

    file_sender = new fileclient;

}
Chat::~Chat()
{
    delete ui;
}
void Chat::on_clearButton_clicked()
{
    ui->textBrowser->clear();
}
void Chat::on_sendButton_clicked()
{
    sendMessage();
}
void Chat::dealClientRead()
{

   m_data.push_back(socket->readAll());

   quint16 len=(m_data[2]<<8&0xFF0)|static_cast<quint16>(m_data[1]);
    if(m_data.size()>=len)
   {
       QByteArray arr=m_data.mid(0,len);
       dealPack(arr);
       m_data=m_data.mid(len);
   }
}

void Chat::dealPack(QByteArray b)
{
    extern User mainuser;
    // 引入实时时间和数据库
    QTime time = QTime::currentTime();
    QSqlQuery query(db);
   //拿到数据
    char cmd=b[3];
    char type=b[4];
    QByteArray arrdata=b.mid(5);
    do
    {
        if(cmd == 0x01)
        {
            break;
        }
        if(cmd == 0x02)
        {
            //我发的
            QString username = mainuser.getName();
            QString currenttime = time.toString("hh:mm:ss");
            QString data = ""+arrdata;
            QString info1 = QString("<b><font size='5' color='blue'>用户：%1 发送 [我] </font></b> <b><font size='4' color='grey'>%2 </font></b><br> <b><font size='4' color='black'>%3 </font></b><br>").arg(username,currenttime,data);
            if(type==0x63)
            {
                ui->textBrowser->append(info1);
            }
            QSound *soundEffect = new QSound(":/sound/send.wav");
            soundEffect->play();
            QString sqlinsert = QString("insert into allmessage values('%1',NULL,'%2','%3',1);").arg(username).arg(data).arg(time.toString("hh:mm:ss"));
            if(!query.exec(sqlinsert)){
                qDebug()<<"记录消息失败";
            }
            else
                qDebug()<<"记录消息成功";
        }
        if(cmd == 0x03)
        {
            //我收到的
            qDebug()<<m_filePath;
            if(type==0x63)
            {
                QString data = ""+arrdata; 
                QString currenttime = time.toString("hh:mm:ss");
                QString info2 = QString("<b><font size='5' color='green'>用户：xxx 发送: </font></b> <b><font size='4' color='grey'>%1 </font></b><br> <b><font size='4' color='black'>%2 </font></b><br>").arg(currenttime,data);
                ui->textBrowser->append(info2);
                QSound *soundEffect = new QSound(":/sound/recieve.wav");
                soundEffect->play();
                QString sqlinsert = QString("insert into allmessage values(NULL,'%1','%2','%3',1);").arg(mainuser.getName()).arg(data).arg(time.toString("hh:mm:ss"));
                if(!query.exec(sqlinsert)){
                    qDebug()<<"记录消息失败";
                }
                else
                    qDebug()<<"记录消息成功";
            }
            else if(type==0x62)
            {
                qDebug()<<"接受文件";
                QString saveFilePath = QFileDialog::getSaveFileName(this, tr("保存文件")); // 打开文件保存对话框
                if (!saveFilePath.isEmpty())
                {
                    QFile file(saveFilePath);
                    if (file.open(QIODevice::WriteOnly))
                    {
                        file.write(arrdata);
                        file.close();
                        ui->textBrowser->append("接收到文件，并保存为：" + saveFilePath);
                    }
                    else
                    {
                        ui->textBrowser->append("保存文件失败");
                    }
                }
            }

        }
    }while(0);
}

void Chat::selectFile()
{
    //file_sender->show();
    m_filePath = QFileDialog::getOpenFileName(this, tr("选择文件")); // 打开文件选择对话框
}
void Chat::sendMessage()
{
    char type=1;
    QByteArray OrignalMessage;
    if(m_filePath=="file")
    {
        OrignalMessage.append(ui->textBox->text());
        ui->textBox->clear();
        type=0x63;
   }
   else
   {
      if (m_filePath.isEmpty()) {
       // 未选择文件时的处理
       // ... 可以弹出消息框提醒用户选择文件
       QMessageBox::warning(this,"提示","请选择文件");
       qDebug()<<m_filePath.isEmpty();

     }
      else if(!m_filePath.isEmpty())
     {
       QFile file(m_filePath);
       qDebug()<<"file open"<<m_filePath;
       bool isopen=file.open(QIODevice::ReadOnly);
       if(!isopen) {
           // 文件打开失败的处理
           // ... 可以弹出消息框提醒用户文件无法打开
           QMessageBox::warning(this,"提示","文件打开失败");
           qDebug()<<isopen;
           return;
       }

       else if(isopen)
       {
           OrignalMessage = file.readAll();
           file.close();
           type=0x62;
       }
       m_filePath="file";
      }
   }
   quint16 l=OrignalMessage.size()+5;
   QByteArray sendbuffer;
   sendbuffer.append(0x66);
   sendbuffer.append(static_cast<char>(l&0x00FF));
   sendbuffer.append(static_cast<char>(l>>8&0x00FF));
   sendbuffer.append(0x03);
   sendbuffer.append(type);
   sendbuffer.append(OrignalMessage);
   socket->write(sendbuffer);
}

void Chat::on_colorpushButton_clicked()//展开选色页面
{
    ui->colorListView->show();
    ui->closeButton->show();        
    ui->changeButton->show();
}

void Chat::on_closeButton_clicked()//关闭选色页面
{
    ui->colorListView->hide();
    ui->closeButton->hide();
    ui->changeButton->hide();
}

void Chat::on_changeButton_clicked()//更换主题
{
    // 将QPalette应用到主窗口
    QModelIndex selectedIndex = ui->colorListView->currentIndex();
        if (selectedIndex.isValid()) {
            QColor selectedColor = selectedIndex.data(Qt::UserRole).value<QColor>();
            QWidget::setPalette(QPalette(selectedColor));
            //加音效
            QSound *soundEffect = new QSound(":/sound/success.wav");
            soundEffect->play();
        }
}
void Chat::on_pushButton_clicked()
{
    this->hide();
}
